package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.ram.model.v20150501.AddUserToGroupRequest;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppUserThreadLocal;
import com.heima.common.util.MD5Utils;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import sun.security.provider.MD5;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-05-19
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService iApUserFollowService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断参数
        if (dto == null || (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (StringUtils.isNotEmpty(dto.getEquipmentId()) && StringUtils.isEmpty(dto.getPhone())) {
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        if (StringUtils.isEmpty(dto.getPhone()) && StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
        query.eq(ApUser::getPhone, dto.getPhone());
        ApUser user = this.getOne(query);
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String password = dto.getPassword() + user.getSalt();
        String passwordStr = DigestUtils.md5DigestAsHex(password.getBytes());
        if (passwordStr.equals(user.getPassword())) {
            String token = AppJwtUtil.getToken(user.getId().longValue());
            user.setPassword(null);
            user.setSalt(null);
            user.setPhone(null);

            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", token);
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //判断用户
        User user = AppUserThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //构建对象
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(user.getUserId());
        //查询用户
        ApUser apUser = this.getById(user.getUserId());
        apUserFollow.setUserName(apUser.getName());
        apUserFollow.setLevel(1);
        apUserFollow.setCreatedTime(new Date());
        //查询作者信息
        ResponseResult<ApAuthor> responseResult = articleFeign.getById(dto.getAuthorId().longValue());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            if (apAuthor != null) {
                apUserFollow.setFollowId(apAuthor.getUserId());
                apUserFollow.setFollowName(apAuthor.getName());

                if (dto.getOperation() == 0) {
                    LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
                    query.eq(ApUserFollow::getUserId, user.getUserId());
                    query.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
                    ApUserFollow follow = iApUserFollowService.getOne(query);
                    if (follow == null) {
                        iApUserFollowService.save(apUserFollow);
                    }
                } else {
                    LambdaQueryWrapper<ApUserFollow> query = new LambdaQueryWrapper<>();
                    query.eq(ApUserFollow::getUserId, user.getUserId());
                    query.eq(ApUserFollow::getFollowId, apAuthor.getUserId());
                    iApUserFollowService.remove(query);
                }
                FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
                behaviorDto.setUserId(user.getUserId());
                behaviorDto.setFollowId(apAuthor.getUserId());
                behaviorDto.setOperation(dto.getOperation());
                behaviorDto.setEquipmentId(dto.getEquipmentId());
                kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(behaviorDto));
            }
        }
        return ResponseResult.okResult();
    }
}
